import { HttpContext } from '@adonisjs/core/http'
import { LucidModel, ModelQueryBuilderContract } from '@adonisjs/lucid/types/model'

export default class BaseController {
  async generatePageData<T extends LucidModel>(
    { request }: HttpContext,
    model: T,
    callback?: (
      query: ModelQueryBuilderContract<T, InstanceType<T>>
    ) => ModelQueryBuilderContract<T, InstanceType<T>>
  ) {
    const page = request.input('page', 1)
    const pageSize = request.input('pageSize', 10)

    let query = model.query()
    if (callback) {
      query = callback(query)
    }

    const result = await query.paginate(page, pageSize)

    const jsonData = result.toJSON()
    delete jsonData.meta.undefined

    return {
      ...jsonData.meta,
      list: jsonData.data,
    }
  }
}
